import sys
from pathlib import Path
 
from PySide6.QtCore import QObject, Slot
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtQuick import QQuickItem
from PySide6.QtWidgets import QApplication, QWidget, QPushButton
# 槽函数类（一个承载槽函数的容器类）
class Slots(QObject):
    def __init__(self, objects):
        self.objects = objects
        super().__init__()
 
    @Slot(str)
    def set_text_msg(self, msg):
        # 获取qml中的Text对象
        child = self.objects[0].findChild(QQuickItem, "text1")
        # 获取对象属性
        p = child.property("text")
        # 设置对象属性
        child.setProperty("text", p + msg)
 
    @Slot(result=str)
    def get_text_msg(self):
        return "皎氯"
 
 
"""
这种方式是以Qml作为窗口来使用。所有的逻辑UI都由Qml来完成。python提供可以调用数据的API即可。
"""
 
 
class LoginQuickWidget:
    def __init__(self):
        # 初始化UI
        self.engine = QQmlApplicationEngine()
        qml_file = str(Path(__file__).resolve().parent / "login.qml")
        # 加载qml文件
        self.engine.load(qml_file)
        if not self.engine.rootObjects():
            sys.exit(-1)
        # qml对象集合
        objects = self.engine.rootObjects()
        # 实例化槽函数
        self.slots = Slots(objects)
        # 注入槽函数
        self.engine.rootContext().setContextProperty('slots', self.slots) 
class TestWidget(QWidget):
    def __init__(self, parent=None):
        super(TestWidget, self).__init__(parent)
        self.button_open = QPushButton(self)
        self.button_open.setText("打开Qml窗口")
        self.button_open.setGeometry(0, 100, 100, 50)
        self.button_open.clicked.connect(self.handle_button_open_click)
        self.button_close = QPushButton(self)
        self.button_close.setText("关闭Qml窗口")
        self.button_close.setGeometry(100, 100, 100, 50)
        self.button_close.clicked.connect(self.handle_button_close_click)
 
    # 打开Qml窗口
    def handle_button_open_click(self):
        self.widget = LoginQuickWidget()
 
    # 关闭Qml窗口
    def handle_button_close_click(self):
        if hasattr(self, 'widget') and self.widget:
            del self.widget
 
 
if __name__ == '__main__':
    app = QApplication([])
    widget = TestWidget()
    widget.show()
    app.exec()